import axios from 'axios'
import router from '@/router'
import { basicRouters } from '@/router'
import { isAuthenticated, getToken, removeToken } from '@/utils/auth'

const whiteList = basicRouters.map((el) => el.name)
// 创建 Axios 实例
const createAxiosInstance = (baseURL) => {
  const instance = axios.create({
    baseURL,
    timeout: 60 * 1000,
  })

  // 请求拦截器
  instance.interceptors.request.use(
    (config) => {
      if (isAuthenticated()) {
        config.headers['Token'] = getToken()
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    },
  )

  // 响应拦截器
  instance.interceptors.response.use(
    (response) => {
      const res = response.data
      const currentRouterName = router.currentRoute.value.name
      if (res.code === 401 && !whiteList.includes(currentRouterName)) {
        removeToken()
        localStorage.clear()
        sessionStorage.clear()
        router.replace('/login')
        return Promise.reject(new Error(res.msg))
      }
      return res
    },
    (error) => {
      // 网络错误
      return Promise.reject(error)
    },
  )

  return instance
}

const baseURL = import.meta.env.VITE_API_ROOT
// 创建请求实例
const request = createAxiosInstance(baseURL)

// 封装请求方法
const service = (options) => {
  const { method = 'get', data, ...rest } = options

  // 处理 GET 请求的 params
  if (method.toLowerCase() === 'get') {
    rest.params = data
  } else {
    rest.data = data
  }
  return request({
    method,
    ...rest,
  })
}

// 支持取消请求
const createCancelToken = () => {
  const source = axios.CancelToken.source()
  return source
}

// 导出请求方法和取消请求的工具
export { service, createCancelToken }
